package com.aube.views;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.util.AttributeSet;
import android.view.View;

import com.aube.R;

/**
 * Created by huyaonan on 16/4/12.
 */
public class RingLoading extends View {

    private int centerX;
    private int centerY;

    private final Paint paint;
    private final Context context;
    private int start=0;
    private static final int PROGRESS = 5;
    private Matrix matrix;
    private int mProgressColor = 0xffff6666;
    private int roundWidth = 10;

    public RingLoading(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        this.paint = new Paint();
        this.paint.setAntiAlias(true); //消除锯齿
        this.paint.setStyle(Paint.Style.STROKE); //绘制空心圆

        mProgressColor = getResources().getColor(R.color.ring_loading_color);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        /**
         * 画最外层的大圆环
         */
        int centre = getWidth()/2; //获取圆心的x坐标
        int radius = centre - roundWidth/2; //圆环的半径
        paint.setStrokeWidth(roundWidth); //设置圆环的宽度

        Shader shader = new SweepGradient(centerX, centerY, Color.TRANSPARENT, mProgressColor);
        paint.setShader(shader);


        matrix = new Matrix();
        matrix.postRotate(start, centerX, centerY);

        canvas.concat(matrix);
        canvas.drawCircle(centre, centre, radius, paint); //画出圆环

        start += PROGRESS;
        invalidate();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh)
    {
        super.onSizeChanged(w, h, oldw, oldh);
        centerX = w / 2;
        centerY = h / 2;
    }


    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);

    }
}